//Package api is the definition of an open interface
//Copyright © 2020 Tim_Paik <timpaik@163.com>
package api

import (
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
)

//Repositories : The definition of json for the software repository
type Repositories struct {
	Name    string `json:"name"`
	Version int64  `json:"version"`
	Update  int64  `json:"update"`
	URL     string `json:"URL"`
	Pkgs    []struct {
		Name    string `json:"name"`
		Version string `json:"version"`
		Update  int    `json:"update"`
		Link    string `json:"link"`
	} `json:"pkgs"`
}

//Read : Read the repo
func Read(path string) (repoJSON []byte, err error) {
	repoJSON, err = ioutil.ReadFile(path)
	return repoJSON, err
}

//Repo : Parse the repo
func Repo(repoJSON []byte) (repo Repositories) {
	json.Unmarshal(repoJSON, &repo)
	return repo
}

//UpdateLocal : Get according to the local repo
func UpdateLocal(repoJSONName string) (err error) {
	json, err := Read(repoJSONName)
	if err != nil {
		return err
	}

	repo := Repo(json)

	err = Update(repo.URL, repoJSONName)
	if err != nil {
		return err
	}

	return nil
}

//Update : Download the repo from URL
func Update(URL string, repoJSONName string) (err error) {
	resp, err := http.Get(URL)
	defer resp.Body.Close()
	if err != nil {
		fmt.Println("Error: Parameter must be full URL or relative path!")
		return err
	}

	out, err := os.Create(repoJSONName)
	defer out.Close()
	if err != nil {
		return err
	}

	_, err = io.Copy(out, resp.Body)
	if err != nil {
		return err
	}

	return nil
}
